package com.github.axet.audiorecorder.simple.activities

import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.BroadcastReceiver
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.widget.Toast
import com.github.axet.androidlibrary.services.StorageProvider
import com.github.axet.audiorecorder.simple.R
import com.github.axet.audiorecorder.simple.app.SimpleStorage
import com.github.axet.audiorecorder.simple.databinding.ActivitySimpleRecordingBinding
import com.github.axet.audiorecorder.simple.recorder.SimpleRecordingManager
import com.github.axet.audiorecorder.simple.services.SimpleRecordingService
import java.io.File

class SimpleRecordingActivity : Activity() {
    
    companion object {
        private const val TAG = "SimpleRecordingActivity"
        private const val PERMISSION_REQUEST_CODE = 1001
        
        private val REQUIRED_PERMISSIONS = arrayOf(
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
        )
    }
    
    private lateinit var binding: ActivitySimpleRecordingBinding
    private var isRecording = false
    private lateinit var recordingManager: SimpleRecordingManager
    
    private val recordingReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val status = intent?.getStringExtra("status")
            
            when (status) {
                "recording" -> {
                    val recordingTime = intent.getLongExtra(SimpleRecordingService.EXTRA_RECORDING_TIME, 0)
                    updateRecordingTime(recordingTime)
                }
                "stopped" -> {
                    val filePath = intent.getStringExtra(SimpleRecordingService.EXTRA_RECORDING_FILE)
                    onRecordingStopped(filePath)
                }
                "error" -> {
                    val errorMessage = intent.getStringExtra(SimpleRecordingService.EXTRA_ERROR_MESSAGE)
                    onRecordingError(errorMessage)
                }
            }
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySimpleRecordingBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        initViews()
        recordingManager = SimpleRecordingManager(this)
        
        if (checkPermissions()) {
            initializeApp()
        } else {
            requestPermissions()
        }
    }
    
    private fun initViews() {
        binding.recordButton.setOnClickListener { toggleRecording() }
        binding.folderButton.setOnClickListener { openRecordingFolder() }
    }
    
    private fun initializeApp() {
        updateUI()
    }
    
    private fun checkPermissions(): Boolean {
        return REQUIRED_PERMISSIONS.all { permission ->
            ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
        }
    }
    
    private fun requestPermissions() {
        ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, PERMISSION_REQUEST_CODE)
    }
    
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        
        if (requestCode == PERMISSION_REQUEST_CODE) {
            val allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
            
            if (allGranted) {
                initializeApp()
            } else {
                Toast.makeText(this, R.string.permission_required, Toast.LENGTH_LONG).show()
                finish()
            }
        }
    }
    
    private fun toggleRecording() {
        if (isRecording) {
            stopRecording()
        } else {
            startRecording()
        }
    }
    
    private fun startRecording() {
        recordingManager.startRecording()
        isRecording = true
        updateUI()
    }
    
    private fun stopRecording() {
        recordingManager.stopRecording()
        isRecording = false
        updateUI()
    }
    
    private fun updateUI() {
        if (isRecording) {
            binding.statusText.setText(R.string.recording)
            binding.recordButton.setText(R.string.stop_recording)
            binding.recordButton.setBackgroundResource(android.R.drawable.btn_default)
        } else {
            binding.statusText.setText(R.string.app_name)
            binding.recordButton.setText(R.string.start_recording)
            binding.recordButton.setBackgroundResource(R.drawable.record_button_background)
            binding.timeText.text = "00:00"
        }
        
        binding.folderButton.isEnabled = !isRecording
        
        // 更新配置信息显示
        updateConfigDisplay()
    }
    
    private fun updateRecordingTime(timeMs: Long) {
        val seconds = (timeMs / 1000).toInt()
        val minutes = seconds / 60
        val remainingSeconds = seconds % 60
        
        val timeString = String.format("%02d:%02d", minutes, remainingSeconds)
        binding.timeText.text = timeString
    }
    
    private fun onRecordingStopped(filePath: String?) {
        isRecording = false
        updateUI()
        
        filePath?.let {
            val file = File(it)
            val message = getString(R.string.recording_saved, file.name)
            Toast.makeText(this, message, Toast.LENGTH_LONG).show()
        }
    }
    
    private fun onRecordingError(errorMessage: String?) {
        isRecording = false
        updateUI()
        
        val message = getString(R.string.recording_error, errorMessage ?: "Unknown error")
        Toast.makeText(this, message, Toast.LENGTH_LONG).show()
    }
    
    private fun updateConfigDisplay() {
        val configInfo = recordingManager.getConfigDisplayText()
        
        // 添加录音统计信息
        val stats = recordingManager.getStorage().getRecordingStats()
        val displayText = if (stats.fileCount > 0) {
            "$configInfo\n已有 ${stats.fileCount} 个录音文件 (${stats.getFormattedSize()})"
        } else {
            configInfo
        }
        
        binding.configText.text = displayText
    }
    
    private fun openRecordingFolder() {
        // 显示选择对话框：今天的录音 vs 所有录音
        AlertDialog.Builder(this)
            .setTitle("选择要打开的文件夹")
            .setItems(arrayOf("今天的录音", "所有录音")) { _, which ->
                when (which) {
                    0 -> openTodayRecordingFolder()
                    1 -> openAllRecordingFolder()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    private fun openTodayRecordingFolder() {
        try {
            val todayDir = recordingManager.getStorage().getTodayRecordingFolder()
            openFolderWithMultipleMethods(todayDir, "今天的录音文件夹")
        } catch (e: Exception) {
            Toast.makeText(this, "打开今天录音文件夹失败: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }
    
    private fun openAllRecordingFolder() {
        try {
            val rootDir = recordingManager.getStorage().getStoragePath()
            openFolderWithMultipleMethods(rootDir, "录音文件夹")
        } catch (e: Exception) {
            Toast.makeText(this, "打开录音文件夹失败: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }
    
    private fun openFolderWithMultipleMethods(targetDir: File, folderDescription: String) {
        try {
            // 确保文件夹存在
            if (!targetDir.exists()) {
                val created = targetDir.mkdirs()
                if (!created) {
                    Toast.makeText(this, "无法创建$folderDescription", Toast.LENGTH_SHORT).show()
                    return
                }
            }
            
            // 尝试多种方式打开文件夹
            var opened = false
            
            // 方式1：使用 StorageProvider
            try {
                val uri = Uri.fromFile(targetDir)
                val intent = StorageProvider.openFolderIntent(this, uri)
                if (intent.resolveActivity(packageManager) != null) {
                    startActivity(intent)
                    opened = true
                }
            } catch (e: Exception) {
                // 忽略，尝试其他方式
            }
            
            // 方式2：使用标准的文件管理器 Intent
            if (!opened) {
                try {
                    val intent = Intent(Intent.ACTION_VIEW)
                    intent.setDataAndType(Uri.fromFile(targetDir), "resource/folder")
                    if (intent.resolveActivity(packageManager) != null) {
                        startActivity(intent)
                        opened = true
                    }
                } catch (e: Exception) {
                    // 忽略，尝试其他方式
                }
            }
            
            // 方式3：使用通用的 ACTION_VIEW
            if (!opened) {
                try {
                    val intent = Intent(Intent.ACTION_VIEW)
                    intent.data = Uri.fromFile(targetDir)
                    if (intent.resolveActivity(packageManager) != null) {
                        startActivity(intent)
                        opened = true
                    }
                } catch (e: Exception) {
                    // 忽略
                }
            }
            
            if (!opened) {
                // 如果都无法打开，显示文件夹路径信息
                showFolderPathDialog(targetDir, folderDescription)
            }
            
        } catch (e: Exception) {
            Toast.makeText(this, "打开${folderDescription}失败: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }
    
    private fun showFolderPathDialog(targetDir: File, folderDescription: String) {
        val message = "${folderDescription}位置:\n${targetDir.absolutePath}\n\n请使用文件管理器手动打开此路径"
        
        AlertDialog.Builder(this)
            .setTitle("文件夹路径")
            .setMessage(message)
            .setPositiveButton("确定", null)
            .setNeutralButton("复制路径") { _, _ ->
                val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                val clip = ClipData.newPlainText("${folderDescription}路径", targetDir.absolutePath)
                clipboard.setPrimaryClip(clip)
                Toast.makeText(this@SimpleRecordingActivity, "路径已复制到剪贴板", Toast.LENGTH_SHORT).show()
            }
            .show()
    }
    
    override fun onResume() {
        super.onResume()
        val filter = IntentFilter(SimpleRecordingService.ACTION_RECORDING_STATUS)
        registerReceiver(recordingReceiver, filter)
    }
    
    override fun onPause() {
        super.onPause()
        unregisterReceiver(recordingReceiver)
    }
    
    override fun onDestroy() {
        super.onDestroy()
    }
}